﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IntelligentGateway.Data;
using IntelligentGateway.Model;
using IntelligentGateway.Model.Panel;
namespace IntelligentGateway.Services.Panel
{
    public class PanelDeviceInfoServices
    {
        private static PanelDeviceInfoDA  deviceDA = new PanelDeviceInfoDA();
        public static bool ProcessHeartBeat(string SN,string ClientIP)
        {
            NetDev dev = new NetDev { DevNo = SN, OnLineTime = DateTime.Now, Status = 1 };
            NetDev ddev = GlobalVariables.PanelDevices.AddOrUpdate(SN, dev, (key, udev) =>
            {
                udev.OnLineTime = dev.OnLineTime;
                udev.Status = 0;
                return udev;
            });
            //Todo:心跳检测增加。
            if (ddev.Status == 1||!ddev.IsUpdateData)
            {
                bool success = false;
                if (deviceDA.CheckDevExist(SN))
                {
                    success = deviceDA.UpdateDevState(new PanelDeviceInfo() { LastStatusTime = ddev.OnLineTime, NO = ddev.DevNo, StateID = 1 });
                }
                else
                {
                    success = deviceDA.InsertDeviceInfo(new PanelDeviceInfo() { Indent = ClientIP,TypeID=1,  LastStatusTime = ddev.OnLineTime, NO = ddev.DevNo, StateID = 1,Memo = "自动注册!" });
                }
                if(success) ddev.IsUpdateData = true;
            }
            return true;
        }
        public static void startCheckHeartBeat()
        {
            deviceDA.UpdateAllDevState();
            Task t = Task.Factory.StartNew(() =>
            {
                List<string> lstRemove = new List<string>();
                NetDev ndev = new NetDev();
                while (true)
                {
                    foreach (var key in GlobalVariables.PanelDevices.Keys)
                    {
                        NetDev netDev = GlobalVariables.PanelDevices[key];
                        if (DateTime.Now.Subtract(netDev.OnLineTime).TotalMinutes > 3)
                        {
                            bool success = deviceDA.UpdateDevState(new PanelDeviceInfo() { LastStatusTime = DateTime.Now, NO = netDev.DevNo, StateID = 2 });
                            if(success) lstRemove.Add(key);
                        }
                    }
                    foreach (var sn in lstRemove)
                    {
                        GlobalVariables.PanelDevices.TryRemove(sn, out ndev);
                    }
                    if (lstRemove.Count > 0) lstRemove.Clear();

                    Task.Delay(10000).Wait();
                }
            });
        }
    }
}
